package com.cm.server.impl;

import com.cm.dto.CreateTemplateDto;
import com.cm.entity.Result;
import com.cm.server.TemplatesService;
import com.cm.utils.ResultEnum;
import com.cm.utils.ResultUtil;
import com.cm.utils.TempStyleUtil;
import org.ofdrw.layout.OFDDoc;
import org.ofdrw.layout.PageLayout;
import org.ofdrw.layout.VirtualPage;
import org.ofdrw.layout.element.Div;
import org.ofdrw.layout.element.Position;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.UUID;

@Service
public class TemplatesImpl implements TemplatesService {

    @Value("${template.file.location}")
    private String TEMP_FILE_PATH;

    private final static Logger logger = LoggerFactory.getLogger(TemplatesImpl.class);

    @Autowired
    TempStyleUtil tempStyleUtil ;

    /**
     * 创建证照模板
     *
     * @param templateInfo 模板信息实体类
     * @return
     */
    @Override
    public Result createTemplate(CreateTemplateDto templateInfo) {
        // 生成唯一ID
        String tempID = String.valueOf(UUID.randomUUID());
        // 生成日期路径
        Calendar now = Calendar.getInstance();
        String path = "/" + now.get(Calendar.YEAR) + "/" + (now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DAY_OF_MONTH);
        // 判断路径是否存在
        File file = new File(TEMP_FILE_PATH + path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        try (OFDDoc ofdDoc = new OFDDoc(Paths.get(TEMP_FILE_PATH + path + "/" + tempID + ".ofd"))) {
            logger.info("开始生成板式文件，地址：" + TEMP_FILE_PATH + path + "/" + tempID + ".ofd");
            /**
             * 样式处理
             */
            if (!tempStyleUtil.styleLoad(ofdDoc,templateInfo)){
                return ResultUtil.error(ResultEnum.TEMP_CREATE_IS_NOT_ERROR.getCode(),ResultEnum.TEMP_CREATE_IS_NOT_ERROR.getMsg()) ;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return ResultUtil.success(templateInfo);
    }

    /**
     * 模板编辑
     *
     * @param tempID 模板ID
     * @return
     */
    @Override
    public Result editor(CreateTemplateDto templateInfo, String tempID) {
        return null;
    }

    /**
     * 模板删除
     *
     * @param tempID 模板ID
     * @param code   邮箱验证码
     * @return
     */
    @Override
    public Result delect(String tempID, String code) {
        return null;
    }

}
